#include "event_app.h"
// #include "safety_app.h"
#include "memory_board.h"
#include "real_time_app.h"
#include "device_parameter.h"

/**
 * @brief 内存单元任务事件回调
 *
 */
static uint16_t MemoryTaskCallback(uint8_t TaskId, uint16_t Events);

static uint8_t MemoryTaskHandle = 0;
static MemoryExternalInterfaces_t MemoryExternalInterfaces = {0};

static uint16_t MemoryTaskCallback(uint8_t TaskId, uint16_t Events)
{
  if (MemoryTaskHandle == TaskId)
  {
    if (Events & SYS_EVENT_MSG)
    {
      uint8_t *pMessage = tmos_msg_receive(MemoryTaskHandle);
      if (pMessage != NULL)
      {
        tmos_msg_deallocate(pMessage);
      }

      return (Events ^ SYS_EVENT_MSG);
    }

    if (Events & UPDATE_DEVICE_PARAM)
    {
      if (MemoryExternalInterfaces.UpdateDeviceParmaeterTask != NULL)
      {
        MemoryExternalInterfaces.UpdateDeviceParmaeterTask();
      }

      return (Events ^ UPDATE_DEVICE_PARAM);
    }
  }

  return 0;
}

uint32_t MemoryGetTimestamp(void)
{
  return RealTimeMakeCurrentTimestamp();
}

void MemoryGetTheCurrentTime(uint16_t *pYr, uint8_t *pMt, uint8_t *pDe, uint8_t *pHr, uint8_t *pMe, uint8_t *pSd, uint8_t *pWk)
{
  RealTimeRtcGetCurrentTime(pYr, pMt, pDe, pHr, pMe, pSd, pWk);
}

void MemoryDeleteAllUserFromExternalModule(void)
{
  // SafetyStartDeletingSpecificUsersTask(PROTOCOL_DUMMY_CODING);
}

void MemoryDeleteSpecificUserFromExternalModule(const uint8_t *pKeyValueIn)
{
  if (pKeyValueIn != NULL)
  {
    uint16_t DeleteUserId = 0;

    DeleteUserId = pKeyValueIn[0] << 8;
    DeleteUserId |= pKeyValueIn[1];
    // SafetyStartDeletingSpecificUsersTask(DeleteUserId);
  }
}

void MemoryMarkLogToBeUpload(void)
{
  EventSetStatusUpdateFlagBit(true);
  EventSetLogNeedToBeUploadedFlagBit(true);
}

void MemoryStopUpdateParameterTask(void)
{
  tmos_stop_task(MemoryTaskHandle, UPDATE_DEVICE_PARAM);
}

void MemoryDelayedStartUpdateParameterTask(uint32_t DelayMs)
{
  tmos_stop_task(MemoryTaskHandle, UPDATE_DEVICE_PARAM);
  tmos_start_task(MemoryTaskHandle, UPDATE_DEVICE_PARAM, DelayMs);
}

void MemoryStartUpdateParameterTaskNoWait(void)
{
  tmos_stop_task(MemoryTaskHandle, UPDATE_DEVICE_PARAM);
  tmos_set_event(MemoryTaskHandle, UPDATE_DEVICE_PARAM);
}

void MemoryBoardInitialisation(MemoryExternalInterfaces_t *pExternalInterfaces)
{
  MemoryExternalInterfaces.UpdateDeviceParmaeterTask = pExternalInterfaces->UpdateDeviceParmaeterTask;
  MemoryTaskHandle = TMOS_ProcessEventRegister(MemoryTaskCallback);
}
